package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.Idea;
import entity.User;
import util.DBHelp;
import util.RowMapper;

public class IdeaDao {

	private DBHelp<Idea> db=new DBHelp<Idea>();
	
	public void save(Idea idea){
		String sql="insert into t_idea (id,title,content,createtime,user_id,project_id) values(?,?,?,?,?,?)";
		db.executeSQL(sql, idea.getId(),idea.getTitle(),idea.getContent(),idea.getCreatetime(),idea.getUser_id(),idea.getProject_id());
	}

	public List<Idea> findAll() {
		String sql="SELECT id,title,content,createtime,project_id,user_id FROM t_idea";
		return db.executeQueryToList(sql, new IdeaRowMapper());
	}
	
	public class IdeaRowMapper implements RowMapper<Idea>{
		public Idea mapRow(ResultSet rs) throws SQLException{
			Idea idea=new Idea();
			idea.setContent(rs.getString("content"));
			idea.setCreatetime(rs.getString("createtime"));
			idea.setId(rs.getString("id"));
			idea.setProject_id(rs.getString("project_id"));
			idea.setUser_id(rs.getString("user_id"));
			idea.setTitle(rs.getString("title"));
			
			
			return idea;
			
		} 
	}

	public Idea findById(String id) {
		String sql="SELECT id,title,content,createtime,project_id,user_id FROM t_idea where id=?";
		return db.executeQueryToObject(sql, new IdeaRowMapper(), id);
	}
	public void del(String id){
		String sql="delete from t_idea where id=?";
		db.executeSQL(sql, id);
	}
	
	public void update(Idea idea){
		String sql="update t_idea set title=?,content=? where id=?";
		 db.executeSQL(sql, idea.getTitle(),idea.getContent(),idea.getId());
		
	}

	public List<Idea> find(){
		String sql="SELECT t_idea.id,title,content,createtime,project_id,user_id,username FROM t_idea  LEFT JOIN t_user ON t_idea.user_id=t_user.id";
		return db.executeQueryToList(sql, new RowMapper<Idea>(){

			public Idea mapRow(ResultSet rs) throws SQLException {
				Idea idea=new Idea();
				
				idea.setContent(rs.getString("content"));
				idea.setCreatetime(rs.getString("createtime"));
				idea.setId(rs.getString("id"));
				idea.setProject_id(rs.getString("project_id"));
				idea.setTitle(rs.getString("title"));
				idea.setUser_id(rs.getString("user_id"));
				
				User user=new User();
				user.setId(rs.getString("user_id"));
				user.setUsername(rs.getString("username"));
				
				idea.setUser(user);
				
				return idea;
			}
			
		});
		
	}
	
}
